<template>
  <view class="monthly-rental-car-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="true" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="月租车管理" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 搜索框 -->
            <view class="filter-item">
              <up-search v-model="searchForm.plateNumber" :clearabled="true" :showAction="true" 
                placeholder="请输入车牌号" @custom="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                  <up-button type="default" size="small" @click="handleClear" style="margin-left: 5px;">重置</up-button>
                </template>
              </up-search>
            </view>
            
            <!-- 状态筛选 -->
            <view class="filter-item">
              <up-dropdown-item v-model="searchForm.status" :options="statusOptions" @change="handleStatusChange" placeholder="状态筛选" />
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 列表内容 -->
      <view class="monthly-rental-car-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              车牌号：<text class="number">{{ item.plateNumber }}</text>
            </view>
            <view class="status" :class="getStatusClass(item.status)">{{ item.statusText }}</view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">生效停车场：</text>
                <text class="value">{{ item.parkingLot }}</text>
              </view>
              <view class="item">
                <text class="label">有效期：</text>
                <text class="value">{{ item.validPeriod }}</text>
              </view>
              <view class="item">
                <text class="label">每日免费时长：</text>
                <text class="value">{{ item.freeHoursPerDay }}小时</text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="primary" text="购买记录" class="custom-style" @click.stop="viewPurchaseRecords(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 购买记录弹窗 -->
    <up-popup v-model:show="showPurchaseRecordsModal" overlay mode="bottom" :round="10" closeable closeOnClickOverlay>
      <view class="purchase-records-modal">
        <view class="modal-title">购买记录</view>
        <view class="modal-content">
          <view class="purchase-record-item" v-for="(record, index) in selectedVehiclePurchaseRecords" :key="index">
            <view class="record-header">
              <view class="record-title">{{ record.plateNumber }}</view>
              <view class="record-status" :class="'record-' + getStatusClass(record.status)">{{ record.statusText }}</view>
            </view>
            <view class="record-content">
              <view class="record-item">
                <text class="record-label">购买时间：</text>
                <text class="record-value">{{ record.purchaseTime }}</text>
              </view>
              <view class="record-item">
                <text class="record-label">购买金额：</text>
                <text class="record-value amount">¥{{ record.amount }}</text>
              </view>
              <view class="record-item">
                <text class="record-label">购买用户：</text>
                <text class="record-value">{{ record.userName }}</text>
              </view>
              <view class="record-item">
                <text class="record-label">月卡信息：</text>
                <text class="record-value">{{ record.cardInfo }}</text>
              </view>
              <view class="record-item">
                <text class="record-label">月租车有效期：</text>
                <text class="record-value">{{ record.validPeriod }}</text>
              </view>
              <view class="record-item">
                <text class="record-label">每天免费时间：</text>
                <text class="record-value">{{ record.freeHoursPerDay }}小时</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 搜索表单
const searchForm = reactive({
  plateNumber: '', // 车牌号
  status: '' // 状态筛选
});

// 状态选项
const statusOptions = [
  { text: '全部', value: '' },
  { text: '正常', value: 'normal' },
  { text: '即将过期', value: 'expiring' },
  { text: '未开始', value: 'notStarted' },
  { text: '禁用', value: 'disabled' },
  { text: '已过期', value: 'expired' }
];

// z-paging 组件引用
const paging = ref(null);

// 当前列表数据
const currentList = ref([]);

// 选中车辆的购买记录
const selectedVehiclePurchaseRecords = ref([]);

// 购买记录弹窗
const showPurchaseRecordsModal = ref(false);

// 处理搜索
const handleSearch = () => {
  paging.value.reload();
};

// 处理清除
const handleClear = () => {
  searchForm.plateNumber = '';
  searchForm.status = '';
  paging.value.reload();
};

// 处理状态变更
const handleStatusChange = () => {
  paging.value.reload();
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  });
};

// 查看购买记录
const viewPurchaseRecords = (item) => {
  // 模拟获取车辆购买记录
  selectedVehiclePurchaseRecords.value = generateMockPurchaseRecords(item);
  showPurchaseRecordsModal.value = true;
  
  // 记录查看记录的操作日志（实际项目中可能需要）
  console.log(`查看车牌号为 ${item.plateNumber} 的购买记录`);
};

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    normal: 'status-normal',
    expiring: 'status-expiring',
    notStarted: 'status-not-started',
    disabled: 'status-disabled',
    expired: 'status-expired'
  };
  return statusMap[status] || '';
};

// 生成模拟购买记录数据
const generateMockPurchaseRecords = (vehicle) => {
  const count = Math.floor(Math.random() * 3) + 1; // 1-3条记录
  return Array.from({ length: count }, (_, i) => ({
    purchaseId: `${Math.floor(Math.random() * 1000000)}`,
    plateNumber: vehicle.plateNumber,
    status: vehicle.status,
    statusText: vehicle.statusText,
    purchaseTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1} ${Math.floor(Math.random() * 24).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}`,
    amount: (Math.random() * 500 + 100).toFixed(2),
    userName: `用户${Math.floor(Math.random() * 1000) + 1}`,
    cardInfo: `${Math.floor(Math.random() * 12) + 1}个月月卡`,
    validPeriod: vehicle.validPeriod,
    freeHoursPerDay: vehicle.freeHoursPerDay
  }));
};

// 查询列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 处理搜索参数
    const params = {
      pageNo,
      pageSize,
      plateNumber: searchForm.plateNumber,
      status: searchForm.status
    };
    
    // 模拟API调用
    // 实际项目中应替换为真实API
    // const result = await getMonthlyRentalCarList(params);
    // const data = result.data;
    
    // 模拟数据
    const mockData = {
      total: 100,
      list: generateMockList(pageNo, pageSize)
    };
    
    // 通知z-paging组件数据加载完成
    paging.value.complete(mockData.list);
  } catch (error) {
    console.error('获取月租车列表数据失败:', error);
    paging.value.complete(false);
  }
};

// 生成模拟列表数据
const generateMockList = (pageNo, pageSize) => {
  // 生成基础数据
  const baseList = Array.from({ length: pageSize }, (_, i) => {
    // 状态定义
    const statusList = ['normal', 'expiring', 'notStarted', 'disabled', 'expired'];
    const statusTextMap = {
      normal: '正常',
      expiring: '即将过期',
      notStarted: '未开始',
      disabled: '禁用',
      expired: '已过期'
    };
    
    // 随机生成状态
    const randomStatus = statusList[Math.floor(Math.random() * statusList.length)];
    
    // 随机生成车牌号
    const randomPlateNumber = `粤${String.fromCharCode(65 + Math.floor(Math.random() * 26))}${Math.floor(Math.random() * 10000).toString().padStart(5, '0')}`;
    
    // 使用筛选条件或随机值
    const status = searchForm.status || randomStatus;
    const plateNumber = randomPlateNumber;
    
    // 生成随机停车场
    const parkingLots = ['南海区中心停车场', '顺德区中心停车场', '禅城区中心停车场', '三水区中心停车场'];
    const parkingLot = parkingLots[Math.floor(Math.random() * parkingLots.length)];
    
    // 生成有效期
    const currentDate = new Date();
    let startDate = new Date(currentDate);
    let endDate = new Date(currentDate);
    
    if (status === 'notStarted') {
      // 未开始状态，开始日期在未来
      startDate.setDate(currentDate.getDate() + Math.floor(Math.random() * 10) + 1);
      endDate.setMonth(startDate.getMonth() + Math.floor(Math.random() * 6) + 1);
    } else if (status === 'expired') {
      // 已过期状态，结束日期在过去
      startDate.setMonth(currentDate.getMonth() - Math.floor(Math.random() * 6) - 2);
      endDate.setDate(currentDate.getDate() - Math.floor(Math.random() * 10) - 1);
    } else if (status === 'expiring') {
      // 即将过期状态，结束日期在近期
      startDate.setMonth(currentDate.getMonth() - Math.floor(Math.random() * 6));
      endDate.setDate(currentDate.getDate() + Math.floor(Math.random() * 5) + 1);
    } else {
      // 正常状态，结束日期在较远的未来
      startDate.setMonth(currentDate.getMonth() - Math.floor(Math.random() * 2));
      endDate.setMonth(currentDate.getMonth() + Math.floor(Math.random() * 6) + 2);
    }
    
    const formatDate = (date) => {
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    };
    
    const validPeriod = `${formatDate(startDate)} 至 ${formatDate(endDate)}`;
    
    // 生成每日免费时长
    const freeHoursPerDay = Math.floor(Math.random() * 12) + 1;
    
    return {
      id: `${pageNo}-${i}`,
      plateNumber,
      status,
      statusText: statusTextMap[status],
      parkingLot,
      validPeriod,
      freeHoursPerDay
    };
  });
  
  // 应用筛选条件
  let filteredList = baseList;
  
  // 车牌号筛选
  if (searchForm.plateNumber) {
    filteredList = filteredList.filter(item => 
      item.plateNumber.includes(searchForm.plateNumber)
    );
  }
  
  // 状态筛选 (已在生成数据时应用)
  
  return filteredList;
};

onMounted(() => {
  // 页面加载时自动加载初始数据
  queryList(1, 10);
});
</script>

<style lang="scss" scoped>
.monthly-rental-car-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .filter-section {
    border-radius: 8px;
    padding: 15px;
  }
}

.monthly-rental-car-list {
  padding: 20px;
}

.purchase-records-modal {
  padding: 25px 20px;
  max-height: 70vh;
  overflow-y: auto;
  
  .modal-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: center;
    color: #333;
    position: relative;
    
    &:after {
      content: '';
      position: absolute;
      bottom: -10px;
      left: 50%;
      transform: translateX(-50%);
      width: 40px;
      height: 3px;
      background-color: #007aff;
      border-radius: 3px;
    }
  }
  
  .modal-content {
    .purchase-record-item {
      background-color: #f8f9fa;
      border-radius: 8px;
      margin-bottom: 15px;
      overflow: hidden;
      
      .record-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 15px;
        background-color: #f0f0f0;
        
        .record-title {
          font-size: 14px;
          font-weight: bold;
        }
        
        .record-status {
          padding: 2px 6px;
          border-radius: 4px;
          font-size: 12px;
        }
        
        .record-status-normal {
          background-color: #e8f5e9;
          color: #4caf50;
        }
        
        .record-status-expiring {
          background-color: #fff8e1;
          color: #ffc107;
        }
        
        .record-status-not-started {
          background-color: #e3f2fd;
          color: #2196f3;
        }
        
        .record-status-disabled {
          background-color: #f5f5f5;
          color: #9e9e9e;
        }
        
        .record-status-expired {
          background-color: #ffebee;
          color: #f44336;
        }
      }
      
      .record-content {
        padding: 10px 15px;
        
        .record-item {
          display: flex;
          margin-bottom: 8px;
          
          .record-label {
            width: 120px;
            color: #666;
            font-size: 13px;
          }
          
          .record-value {
            flex: 1;
            color: #333;
            font-size: 13px;
            
            &.amount {
              color: #f56c6c;
              font-weight: bold;
            }
          }
        }
      }
    }
  }
}
</style>